package com.hsgc.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hsgc.info.ImgInfo;
import com.hsgc.info.UploadInfo;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/upload")
public class UploadController {

    //两个参数  name 和base64
    @PostMapping
    public String upload(@RequestBody UploadInfo uploadInfo){
        String name=uploadInfo.getName();
        String base64 =uploadInfo.getBase64();
        String[] base64s = StrUtil.splitToArray(base64, "base64,");
        //字符转换为字节
        byte[] bytes = Base64.decode(base64s[1]);
        //使用hutool里面的雪花算法
        name = IdUtil.getSnowflakeNextIdStr() + "_" + name;

        //写入到nginx
        FileUtil.writeBytes(bytes,"D:/software/nginx-1.21.4/html/images/"+name);


        return "http://www.hphs.com/images/"+name;
    }

    @GetMapping
    public List<ImgInfo> getImage(){
        //获取图片的目录文件
        List<String> fileNames = FileUtil.listFileNames("D:/software/nginx-1.21.4/html/images/");
        List<ImgInfo> collect = fileNames.stream().map(
                item -> {
                    return new ImgInfo(item, "http://www.hphs.com/images/" + item);
                }).collect(Collectors.toList());
        return collect;
    }

}
